﻿/**************************************************
 *  Author :    youping
 *  CreateDate: 2021-06-20
 *  Title:      文件相关操作
**************************************************/

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Demo.FolderOp
{
    public class FileMethod
    {
        public delegate void DelegateProgressBar(int pro);
        private static Dictionary<string, List<string>> myExistsImgDic = null;
        FileMethod() {
            myExistsImgDic = new Dictionary<string, List<string>>();
        }

        #region 从指定位置复制文件(包括文件夹)到目标地址
        /// <summary>
        /// 从指定位置复制文件(包括文件夹)到目标地址
        /// </summary>
        /// <param name="whereUrl"></param>
        /// <param name="targetUrl"></param>
        /// <returns></returns>
        public static bool DocumentCopyToTargetLocation(string whereUrl, string targetUrl, DelegateProgressBar func)
        {
            bool result = true;
            string message = string.Empty;
            string paramTargetUrl = string.Empty;
            try
            {
                //复制文件到对应目录
                string[] myFiles = Directory.GetFiles(whereUrl);

                foreach (string myFile in myFiles)
                {
                    if (File.Exists(myFile))
                    {
                        File.Copy(myFile, targetUrl + myFile.Substring(myFile.LastIndexOf('\\'), (myFile.Length - myFile.LastIndexOf('\\'))), true);
                        func(1);
                    }
                    else
                    {
                        message += myFile + "路径的文件不存在！<br />";
                    }
                }

                //打开文件夹，复制文件目录‘
                string[] myDirectories = Directory.GetDirectories(whereUrl);
                foreach (string myDirectory in myDirectories)
                {
                    paramTargetUrl = targetUrl + myDirectory.Substring(myDirectory.LastIndexOf('\\'), (myDirectory.Length - myDirectory.LastIndexOf('\\')));
                    if (!Directory.Exists(paramTargetUrl))
                    {
                        Directory.CreateDirectory(paramTargetUrl);
                    }
                    if (!DocumentCopyToTargetLocation(myDirectory, paramTargetUrl, func))
                    {
                        message += myDirectory + "路径内数据复制失败！<br />";
                    }
                }
            }
            catch (Exception myEx)
            {
                result = false;
                throw myEx;
            }
            return result;
        }
        #endregion

        #region 计算文件夹内文件总个数
        /// <summary>
        /// 计算文件夹内文件总个数
        /// </summary>
        /// <param name="folderUrl"></param>
        /// <returns>返回文件个数</returns>
        public static int GetFolderFileCount(string folderUrl)
        {
            int result = 0;
            //判断路径是否存在
            if (!Directory.Exists(folderUrl))
            {
                return result;
            };
            //判断路径下面文件个数
            string[] myTempArr = Directory.GetFiles(folderUrl);
            result = myTempArr.Length;

            //查询路径下文件夹
            myTempArr = Directory.GetDirectories(folderUrl);
            foreach (string myDirectory in myTempArr)
            {
                //判断文件夹目标是否存在
                result += GetFolderFileCount(folderUrl + myDirectory.Substring(myDirectory.LastIndexOf('\\'), (myDirectory.Length - myDirectory.LastIndexOf('\\'))));
            }
            return result;
        }
        #endregion

        #region 判断文件内文件是否存在
        /// <summary>
        /// 
        /// </summary>
        /// <param name="folderUrl"></param>
        /// <returns>true 存在， false 不存在</returns>
        public static bool CheckFolderFileExists(string folderUrl)
        {
            bool isExists = false;
            //判断路径是否存在
            if (!Directory.Exists(folderUrl))
            {
                return isExists;
            };
            //判断路径下面文件个数
            string[] myTempArr = Directory.GetFiles(folderUrl);
            if (myTempArr.Length > 0)
            {
                isExists = true;
                return isExists;
            }

            //查询路径下文件夹
            myTempArr = Directory.GetDirectories(folderUrl);
            foreach (string myDirectory in myTempArr)
            {
                if (CheckFolderFileExists(folderUrl + myDirectory.Substring(myDirectory.LastIndexOf('\\'), (myDirectory.Length - myDirectory.LastIndexOf('\\')))))
                {
                    isExists = true;
                    break;
                }
                //判断文件夹目标是否存在
            }
            return isExists;
        }
        #endregion

        #region 查找目录下面的所有图片文件
        public static bool InitFileMethod()
        {
            myExistsImgDic = new Dictionary<string, List<string>>();
            return true;
        }
        private static bool CheckImgSimilar(List<string> oldUrlList, string newUrl)
        {
            bool result = false;
            try
            {
                foreach (string oldUrl in oldUrlList)
                {
                    //CheckImgSize(newUrl, 1000 )
                    if (ImgManager.ImgMethod.CheckImgSimilar(oldUrl, newUrl))
                    {
                        result = true;
                        break;
                    }
                }
                return result;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        #region 判断格式是否满足，判断大小是否符合条件
        /// <summary>
        /// 判断格式是否满足，判断大小是否符合条件
        /// </summary>
        /// <param name="path"></param>
        /// <param name="myFilterList"></param>
        /// <param name="minImgSize"></param>
        /// <returns>满足返回true</returns>
        private static bool CheckImgRight(string path, List<string> myFilterList, int minImgSize)
        {
            bool result = false;
            try
            {
                //判断格式是否满足要求
                bool isRight = false;
                //打开文件
                FileInfo fileInfo = new FileInfo(path);
                foreach (string temp in myFilterList)
                {
                    if (fileInfo.Extension.ToLower() == temp.ToLower())
                    {
                        isRight = true;
                        break;
                    }
                }
                if (!isRight)
                {
                    return false;
                }

                //判断格式大小是否满足要求
                // 获取图片文件的大小（以字节为单位）  
                long fileSize = fileInfo.Length;
                if (fileSize >= minImgSize * 1000)
                {
                    return true;
                }
            }
            catch (Exception ex)
            {
                result = false;
            }
            return result;
        }
        #endregion 
        private static bool CheckImgSize(string path, int minImgSize)
        {
            bool result = false;
            try
            {
                //打开文件
                FileInfo fileInfo = new FileInfo(path);
                // 获取图片文件的大小（以字节为单位）  
                long fileSize = fileInfo.Length;
                if (fileSize >= minImgSize * 1000)
                {
                    result = true;
                }
            }
            catch (Exception ex)
            {
                result = false;
            }
            return result;
        }
        public static bool GetImgInfo(string whereUrl, string targetUrl, List<string> filter, int minImgSize)
        {
            bool result = true;
            string message = string.Empty;
            try
            {
                // string 名字， 路径地址  ----- 文件夹内过滤数据
                //Dictionary<string, List<string>> myExistsImgDic = new Dictionary<string, List<string>>();
                //打开文件夹，查询对应文件夹是否存在图片
                string[] myFiles = Directory.GetFiles(whereUrl);
                List<string> myList = null;
                string tempName = string.Empty; //文件存储名称\\xxx.jpg
                string tempFileName = string.Empty; //文件名称 xxx.jpg

                foreach (string myFile in myFiles)
                {
                    if (!CheckImgRight(myFile, filter, minImgSize))
                    {
                        continue;
                    }

                    tempName = myFile.Substring(myFile.LastIndexOf('\\'), (myFile.Length - myFile.LastIndexOf('\\')));
                    tempFileName = tempName.TrimStart('\\');
                    //如果目的地存在相同文件名字的图片
                    if (File.Exists(targetUrl + tempName))
                    {
                        if (File.Exists(myFile))
                        {
                            if (!myExistsImgDic.ContainsKey(tempFileName))
                            {
                                myList = new List<string>();
                                myList.Add(targetUrl + tempName);
                                myExistsImgDic.Add(tempFileName, myList);
                            }
                            // 如果图片相似，则返回继续；
                            if (CheckImgSimilar(myExistsImgDic[tempFileName], myFile))
                            {
                                continue;
                            }
                            //建立名字文件字典

                            if (!myExistsImgDic.ContainsKey(tempFileName))
                            {
                                myList = new List<string>();
                                myList.Add(myFile);
                                myExistsImgDic.Add(tempFileName, myList);
                            }
                            else
                            {
                                //更新数据源
                                myList = myExistsImgDic[tempFileName];
                                myList.Add(myFile);
                                myExistsImgDic[tempFileName] = myList;
                            }
                            string[] tempValArr = tempName.Split('.');
                            File.Copy(myFile, targetUrl + tempValArr[0] + "_" + DateTime.Now.ToString("yyyyMMddHHmmssfffffff") + "." + tempValArr[1], true);
                        }
                        else
                        {
                            message += myFile + "路径的文件不存在！<br />";
                        }
                    }
                    else
                    {
                        if (File.Exists(myFile))
                        {
                            //建立名字文件字典
                            if (!myExistsImgDic.ContainsKey(tempFileName))
                            {
                                myList = new List<string>();
                                myList.Add(myFile);
                                myExistsImgDic.Add(tempFileName, myList);
                            }
                            File.Copy(myFile, targetUrl + myFile.Substring(myFile.LastIndexOf('\\'), (myFile.Length - myFile.LastIndexOf('\\'))), true);
                        }
                        else
                        {
                            message += myFile + "路径的文件不存在！<br />";
                        }
                    }
                }
                string[] myDirectories = Directory.GetDirectories(whereUrl);
                foreach (string myDirectory in myDirectories)
                {
                    if (!GetImgInfo(myDirectory, targetUrl, filter, minImgSize))
                    {
                        message += myDirectory + "路径内数据复制失败！<br />";
                    }
                }
            }
            catch (Exception ex)
            {
                message += ex.Message;
                result = false;
            }
            return result;
        }
        #endregion
    }
}
